<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号" prop="goodsNo">
        <el-input
          v-model="queryParams.goodsNo"
          placeholder="请输入编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品单价" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入商品单价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商库存" prop="supplierStock" label-width="100px">
        <el-input
          v-model="queryParams.supplierStock"
          placeholder="请输入供应商库存"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['supplier:goodsManage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supplier:goodsManage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supplier:goodsManage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['supplier:goodsManage:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsManageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品主键" align="center" prop="goodsId" />
      <el-table-column label="编号" align="center" prop="goodsNo" />
      <el-table-column label="名称" align="center" prop="goodsName" />
      <el-table-column label="简介" align="center" prop="goodsDesc" />
      <el-table-column label="商品类别" align="center" prop="goodsType" />
      <el-table-column label="商品单价" align="center" prop="price" />
      <el-table-column label="供应商库存" align="center" prop="supplierStock" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="{ row }">
          {{ row.status === '1' ? '起售' : '停售' }}
        </template>
      </el-table-column>
      <el-table-column label="商品库存" align="center" prop="goodsStock" />
      <el-table-column label="商品图片" align="center" prop="goodsPicture" >
        <template slot-scope="{ row }">
          <img
            width="50px"
            height="50px"
            v-if="row.goodsPicture"
            :src="getImage(row.goodsPicture)"
            class="avatar"
          ></img>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['supplier:goodsManage:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['supplier:goodsManage:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="编号" prop="goodsNo">
          <el-input v-model="form.goodsNo" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="简介" prop="goodsDesc">
          <el-input v-model="form.goodsDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商品单价" prop="price">
          <el-input v-model="form.price" placeholder="请输入商品单价" />
        </el-form-item>
        <el-form-item label="商品种类" prop="price">
          <el-input v-model="form.goodsType" placeholder="请输入商品类别" />
        </el-form-item>
        <el-form-item label="商品状态" prop="price">
          <el-input v-model="form.status" placeholder="请输入商品状态 1起售 0停售" />
        </el-form-item>
        <el-form-item label="供应商库存" prop="supplierStock">
          <el-input v-model="form.supplierStock" placeholder="请输入供应商库存" />
        </el-form-item>
        <el-form-item
          label="商品图片:"
          prop="region"
          class="uploadImg"
        >
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/system/common/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-change="onChange"
            ref="upload"
          >
            <img
              width="50px"
              height="50px"
              v-if="form.goodsPicture"
              :src="getImage(form.goodsPicture)"
              class="avatar"
            ></img>
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            ></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGoodsManage,
  getGoodsManage,
  delGoodsManage,
  addGoodsManage,
  updateGoodsManage,
  getGoodsStock
} from "@/api/supplier/goodsManage";
import GoodPicture from "@/views/supplier/goodsManage/component/goodPicture.vue";
import user from "@/store/modules/user";
import {isNumberStr} from "@/utils";

export default {
  name: "GoodsManage",
  components: {GoodPicture},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      goodsManageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsNo: null,
        goodsName: null,
        goodsDesc: null,
        supplierId: user.state.id,
        goodsType: null,
        price: null,
        supplierStock: null,
        status: null,
        goodsPicture: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        supplierId: [
          { required: true, message: "供货商id不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      console.log(user.state.id)
      listGoodsManage(this.queryParams).then(response => {
        this.goodsManageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      console.log(this.goodsManageList[0].status)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        goodsId: null,
        goodsNo: null,
        goodsName: null,
        goodsDesc: null,
        supplierId: user.state.id,
        goodsType: null,
        goodsStock: null,
        price: null,
        createTime: null,
        updateTime: null,
        updateBy: null,
        status: 1,
        goodsPicture: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.goodsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const goodsId = row.goodsId || this.ids
      getGoodsManage(goodsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.goodsNo == null || !isNumberStr(this.form.goodsNo)) {
        console.log("请在编号框输入数字")
        this.$modal.msgError({
          title: '错误',
          message: '请在编号框输入数字'
        });
        return;
      }
      if (parseInt(this.form.supplierStock).toString() !== this.form.supplierStock.toString() ||
        parseInt(this.form.supplierStock) <= 0 || parseInt(this.form.supplierStock) >= 2000000) {
        this.$modal.msgError({
          title: '错误',
          message: '请输入大于0小于200000的整数库存'
        });
        return;
      }
      if ((parseInt(this.form.price).toString() !== this.form.price && parseInt(this.form.price) !== this.form.price) ||
        parseInt(this.form.price) <= 0 || parseInt(this.form.price) >= 2000000) {
        this.$modal.msgError({
          title: '错误',
          message: '请在输入大于0小于200000的价格'
        });
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.supplierId = user.state.id;
          if (this.form.goodsId != null) {
            updateGoodsManage(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoodsManage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const goodsIds = row.goodsId || this.ids;
      this.$modal.confirm('是否确认删除商品编号为"' + goodsIds + '"的数据项？').then(function() {
        return delGoodsManage(goodsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('supplier/goodsManage/export', {
        ...this.queryParams
      }, `goodsManage_${new Date().getTime()}.xlsx`)
    },
    handleAvatarSuccess (response, file, fileList) {
      // 拼接down接口预览
      this.form.goodsPicture = `${response.data}`
      console.log(this.imageUrl)
    },
    onChange (file) {
      if(file){
        const suffix = file.name.split('.')[1]
        const size = file.size / 1024 / 1024 < 2
        if(['png','jpeg','jpg'].indexOf(suffix) < 0){
          this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
          this.$refs.upload.clearFiles()
          return false
        }
        if(!size){
          this.$message.error('上传文件大小不能超过 2MB!')
          return false
        }
        return file
      }
    },
    getImage (image) {
      return `http://localhost:8080/system/common/download?name=${image}`
    },
  }
};
</script>
